# --*-- conding:utf-8 --*--
# @Time : 2025/6/18 10:39
# @Author : Xu
# @Email : wsxzy98@outlook.com
# @File : stock_move.py
# @Software : VScode

# --*-- coding:utf-8 --*--
from odoo import models, fields, api

class StockMove(models.Model):
    _inherit = 'stock.move'

    origin_name = fields.Char(string='原产地')
    origin_country_id = fields.Many2one('res.country', string='原产地')#千万不能删！

    # 新增：产品内部参考号和描述字段
    prodotto_id = fields.Char(string='产品')  # 用于保存产品的 default_code
    #prodotto_id = fields.Many2one('product.product', string='产品编号')
    descrizione = fields.Char(string='描述')  # 用于保存产品名称

    @api.model
    def create(self, vals):
        # 自动带出产品主数据 origin
        if not vals.get('origin_name') and vals.get('product_id'):
            prod = self.env['product.product'].browse(vals['product_id'])
            if prod and prod.product_tmpl_id.origin:
                vals['origin_name'] = prod.product_tmpl_id.origin
        # 自动同步产品编号和描述
        if vals.get('product_id'):
            product = self.env['product.product'].browse(vals['product_id'])
            vals['prodotto_id'] = product.default_code or ''
            vals['descrizione'] = product.name or ''
        return super().create(vals)
    

    @api.onchange('product_id')
    def _onchange_product_id_origin_name(self):
        # 产品变化自动同步 origin_name
        if self.product_id and not self.origin_name:
            self.origin_name = self.product_id.product_tmpl_id.origin
        # 当产品发生变化时，自动同步内部编号和描述
        if self.product_id:
            self.prodotto_id = self.product_id.default_code or ''
            self.descrizione = self.product_id.name or ''
        else:
            self.prodotto_id = ''
            self.descrizione = ''

    def write(self, vals):
        res = super().write(vals)
        if 'origin_name' in vals:
            for move in self:
                if move.product_id:
                    move.product_id.product_tmpl_id.origin = vals['origin_name']
        # 同步内部编号与描述（如果改了 product_id）
        if 'product_id' in vals:
            for move in self:
                if move.product_id:
                    move.prodotto_id = move.product_id.default_code or ''
                    move.descrizione = move.product_id.name or ''
        return res
    
    # —— 关键点：把 customer_reference 透传到整条调用栈 ——

    def _action_assign(self, *args, **kwargs):
        """按 picking 分组，带着 customer_reference 调 super，从而让 Quant 预留走 ref 维度。"""
        # Odoo 18 这里通常返回 None；为兼容，这里聚合 super 的返回值
        results = []
        # 有些 move 可能没有 picking（极少），这些直接走 super 不带上下文
        no_pick = self.filtered(lambda m: not m.picking_id)
        if no_pick:
            results.append(super(StockMove, no_pick)._action_assign(*args, **kwargs))

        for picking in self.mapped('picking_id'):
            moves = self.filtered(lambda m: m.picking_id == picking)
            ctx = dict(self.env.context, customer_reference=picking.customer_reference or False)
            results.append(super(StockMove, moves.with_context(ctx))._action_assign(*args, **kwargs))
        # 兼容不同版本的返回类型
        return next((r for r in results if r), None)

    def _action_done(self, cancel_backorder=False):
        """完结也同样带 context，让 Quant 增减都以 ref 为粒度产生/合并。"""
        done_moves = self.browse()

        no_pick = self.filtered(lambda m: not m.picking_id)
        if no_pick:
            done_moves |= super(StockMove, no_pick)._action_done(cancel_backorder=cancel_backorder)

        for picking in self.mapped('picking_id'):
            moves = self.filtered(lambda m: m.picking_id == picking)
            ctx = dict(self.env.context, customer_reference=picking.customer_reference or False)
            done_moves |= super(StockMove, moves.with_context(ctx))._action_done(cancel_backorder=cancel_backorder)

        return done_moves


    # def write(self, vals):
    #     # 写入后同步到产品主数据
    #     res = super().write(vals)
    #     if 'origin_name' in vals:
    #         for move in self:
    #             if move.product_id:
    #                 move.product_id.product_tmpl_id.origin = vals['origin_name']
    #     res = super().write(vals)
    #     for move in self:
    #         if 'product_id' in vals and move.product_id:
    #             move.prodotto_id = move.product_id.default_code or ''
    #             move.descrizione = move.product_id.name or ''
    #     return res
